<template>
    <div class="cart">
        <CommonHeader teleport=".header" @click-left="$router.push('/')">
            <template #left>
                <van-icon name="home-o" />
            </template>
            <template #right>
                <van-popover v-model:show="showPopover" :actions="actions" placement="bottom-end" theme="dark">
                    <template #reference>
                        <van-icon name="ellipsis" />
                    </template>
                </van-popover>
            </template>
        </CommonHeader>

        <div class="cart-list">
            <van-swipe-cell v-for="item in cartList" :key="item.cartid">
                <van-card :price="(item.originprice * item.discount / 10).toFixed(2)" :desc="item.desc"
                    :title="item.proname" :origin-price="item.originprice">
                    <template #thumb>
                        <van-checkbox v-model="item.flag" @change="selectOneChange($event, item.cartid)"></van-checkbox>
                        <van-image width="95" height="95" :src="item.img1" />
                    </template>
                    <template #tags>
                        <van-tag plain type="primary" v-if="item.discount < 10">折扣</van-tag>
                    </template>
                    <template #num>
                        <van-stepper v-model="item.num" integer theme="round"
                            @change="numChangeHandler($event, item.cartid)" />
                    </template>
                    <template #footer>
                        <span>收藏</span> |
                        <span @click="delOneHandler(item.cartid)">删除</span>
                    </template>
                </van-card>
                <template #right>
                    <van-button square type="danger" text="删除" @click="delOneHandler(item.cartid)" />
                </template>
            </van-swipe-cell>

        </div>
        {{ total }}
        <van-submit-bar :price="total * 100" button-text="去结算" @submit="onSubmit">
            <!-- 权限 -->
            <van-checkbox v-model="isCheckedAll">全选</van-checkbox>
        </van-submit-bar>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';

import { getCartListAPI, updateNumAPI, removeOneAPI, selectOneAPI } from '@/api/cart';
import { addOrderAPI } from '@/api/order';
import { useUserid } from "@/hooks/useUserid"
import { showFailToast, showSuccessToast, closeToast } from 'vant';
import { showConfirmDialog } from 'vant';

import { useRouter } from 'vue-router';



// console.log(useUserid());

const { userid } = useUserid();
const router = useRouter();


let showPopover = ref<boolean>(false);
const actions = [
    { text: '选项一', icon: 'add-o' },
    { text: '选项二', icon: 'music-o' },
    { text: '选项三', icon: 'more-o' },
];

const cartList = ref<any>(null);

const isCheckedAll = computed({
    get() {
        if (cartList.value) {
            var flag = cartList.value.every((v: any) => v.flag == true);
            return cartList?.value?.length > 0 ? flag : false;
        } else {
            return false;
        }

    },
    set(val) {
        if (cartList.value) {
            cartList.value.forEach((v: any) => v.flag = val)
        }
    }
})

const total = computed(() => {
    if (cartList.value) {
        return cartList.value.reduce((prev: number, item: any) => item.flag ? prev + (item.originprice * item.discount / 10) * item.num : prev, 0).toFixed(2);
    } else {
        return 0;
    }
})


const getCartList = async () => {
    try {
        let result = await getCartListAPI({ userid: userid.value });
        console.log("购物车成功", result.data);

        cartList.value = result.data;
    } catch (err: any) {
        showFailToast(err.message);
    }
}

const numChangeHandler = async (num: string, cartid: string) => {
    console.log("num", num);
    console.log("cartid", cartid);
    try {
        let result = await updateNumAPI({
            cartid,
            num,
        });
        console.log("数量更新成功", result.data);

        closeToast();
        showSuccessToast("数量更新成功");
    } catch (err: any) {
        showFailToast(err.message);
    }

}

const delOneHandler = async (cartid: string) => {

    await showConfirmDialog({
        title: "提示",
        message: "是否删除该商品?"
    })


    try {

        let index = cartList.value.findIndex((v: any) => v.cartid == cartid);
        cartList.value.splice(index, 1);
        console.log("cartid", cartid);

        let result = await removeOneAPI({
            cartid,
        });
        console.log("删除成功", result.data);

        closeToast();
        showSuccessToast("删除成功");
    } catch (err: any) {
        showFailToast(err.message);
    }

}

const selectOneChange = async (flag: boolean, cartid: string) => {
    try {
        let result = await selectOneAPI({
            cartid,
            flag,
        });
        console.log("check更新成功", result);
    } catch (err: any) {
        showFailToast(err.message);
    }
}

const onSubmit = async () => {
    var arr = cartList.value.filter((v: any) => v.flag == true);

    if (arr.length > 0) {

        try {
            let result = await addOrderAPI({
                userid:userid.value,
            });
            console.log("加入订单成功", result);
            router.push({path:"/order/confirm",query:{time:(result as any).time}})

        } catch (err: any) {
            showFailToast(err.message);
        }

    } else {
        showFailToast("您还未选择任何商品!");
    }
}


onMounted(() => {
    getCartList();
})


</script>

<style lang="scss" scoped>
.cart {
    padding-bottom: 50px;
}

:deep(.van-card__thumb) {
    width: 120px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

:deep(.van-swipe-cell__right) {
    display: flex;
    align-items: center;
    background-color: #ee0a24;
}
</style>